import { dom, _query, _addClassName, _queryAll, _removeClassName } from './dom.js'
import { _playBar } from './playBar.js'
import { plainTreeMenu } from '../utils/index.js'
import { _tree } from './tree.js'
import {
    getRoute
} from './route.js'
import { _g2 } from './g2.js'
import { _navTree, clickTreeItem, setNavTreeConfig } from './navTree.js'
import { showAside, hideAside } from './aside.js'
import { store } from '../store/index.js'


export const _nav = (treeData, config = {}) => {
    let { target, root = document.body } = config //activeName
    let list = plainTreeMenu(treeData)
    setNavTreeConfig({
        target,
        root
    })

    let buildNavTree = (data) => {
        _navTree({ name: data.name, data: data.children })
    }

    let initNavRoot = (name, enterFromUrl) => {
        let item = list.find(t => t.name === name)
        if (item && item.contentType) {
            let data = treeData.find(t => t.name === item.contentType)
            setTimeout(() => {
                let items = _queryAll(".nav .nav-item")
                _removeClassName(items, 'active')

                let el = _query(`.nav-item[role="${item.contentType}"]`)
                _addClassName(el, 'active')
            })

            buildNavTree(data)
            clickTreeItem(item, enterFromUrl)
        }
    }




    let render = (t) => {
        return dom.div(t.title, {
            class: 'nav-item',
            role: t.name
        }, (e) => {
            showAside()

            let items = _queryAll(".nav-item")
            _removeClassName(items, "active")
            let el = e.target
            _addClassName(el, 'active')
            buildNavTree(t)
        })
    }

    let nav = _tree(treeData, render, 0)

    let playBar = _playBar(list, (t) => {
        hideAside()
        let navtree = _query(".aside .navtree")
        if (navtree) {
            // 显示菜单 模式
            initNavRoot(t.name, false)
        } else {
            // 隐藏菜单 模式
            clickTreeItem(t, false)
        }
    })

    // 初始化路由
    let route = getRoute()
    if (route) {
        // activeName = route
        initNavRoot(route, true)
    }

    let tools = dom.div(store.isH5 ? playBar : [playBar, _g2()], {
        class: 'nav-right'
    })

    return dom.div([nav, tools], {
        class: "nav"
    })
}